package com.chazz.servlet.ljh;

import com.alibaba.fastjson.JSON;
import com.chazz.dto.Message;
import com.chazz.dto.OrderAdress;
import com.chazz.entity.*;
import com.chazz.service.ljh.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ljh/order/*")
public class OrderServlet extends BaseController {

    OrderServiceImpl orderServiceImpl = new OrderServiceImpl();

    /**
     * 查询user的收货地址和user的电话号码和名字
     */
    public void getAddress(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        //从session拿user
        HttpSession session = request.getSession();
        User  user = (User) session.getAttribute("user");
        //实例化一个OrderAdress
        OrderAdress orderAdress = new OrderAdress();
        //拿到user，获取到username和电话phone以及id
//        String username = "张三"; //user.getUsername();
//        String phone = "12343545";//user.getPhone();
//        int id = 1; //user.getId();
        //通过id到adress表去找user的收货地址，注意：拿到的是个list集合
        List<String> list = orderServiceImpl.getAddress(user.getId());
        System.out.println(list);
        //把查到的放入orderAddress对象里
        orderAdress.setAdress(list);
        orderAdress.setPhone(user.getPhone());
        orderAdress.setUserName(user.getUsername());
        session.setAttribute("orderAdress",orderAdress);
        //把orderAdress对象装换成json
        String json = JSON.toJSONString(orderAdress);
        System.out.println(json);
        //将json响应给客户端
        response.getWriter().write(json);
    }

    /**
     * 获取user的购买商品的全部信息
     */
    public void getGoodMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        //从session里获取user的id
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        //通过user的id，去order表查到商品详情表id
        Orders order = orderServiceImpl.getOid(user.getId());
        System.out.println("oid =" + order.getId());
        int oid = order.getId();
        //通过oid去orderdetails表里找gid，注意返回的是list
        List<Orderdetails> orderdetails = orderServiceImpl.getGid(oid);
        List<Integer> gid = new ArrayList<>();
        for (Orderdetails temp : orderdetails) {
            gid.add(temp.getGid());
        }
        System.out.println("gid =" + gid);
        //拿到gid去goods表查找商品信息
        List<Goods> goods = new ArrayList<Goods>();
        goods = orderServiceImpl.getGoodMessage(gid);
        System.out.println(goods);

        //从goods里拿分类id
        List<Integer> categoryId = new ArrayList<>();
        for (Goods temp : goods) {
            categoryId.add(temp.getCategoryid());
        }
        //到商品分类表查询分类信息
        List<Category> categorys = new ArrayList<>();
        categorys = orderServiceImpl.getCategory(categoryId);
        System.out.println("分类表信息：" + categorys);


        //从goods里拿到品牌id，在去查找品牌信息
        List<Integer> brandId = new ArrayList<>();
        for (Goods temp : goods) {
            brandId.add(temp.getBrandid());
        }
        List<Brand> brands = orderServiceImpl.getBrand(brandId);
        System.out.println("品牌表信息：" + brands);
        // 从商品分类的主键id，去Attributekey去查询

        List<Attributekey> attributekeys = orderServiceImpl.getAttributekey(categoryId);
        System.out.println("属性表信息：" + attributekeys);


        //从Attributekey表里拿到主键id，去查询value
        List<Integer> attributeId = new ArrayList<>();
        for (Attributekey temp : attributekeys) {
            attributeId.add(temp.getAttributeid());
        }
        //去value表查询
        List<Value> values = orderServiceImpl.getValue(attributeId);
        System.out.println("value值的信息：" + values);
        //查规格表
        List<Sku> skus = orderServiceImpl.getSku(gid);
        System.out.println("规格表的信息 ：" + skus);

        //实例化一个消息类，在传到前端。
        List<Message> messages = new ArrayList<>();
        for (int i = 0; gid.size() > i; i++) {
            Message message = new Message();
            message.setCategoryimg(categorys.get(i).getCategoryimg());
            System.out.println("img:" + categorys.get(i).getCategoryimg());
            message.setGoodsdescription(goods.get(i).getGoodsdescription());
            System.out.println("描述：" + goods.get(i).getGoodsdescription());
            message.setGoodsattribute(skus.get(i).getGoodsattribute());
            System.out.println("规格：" + skus.get(i).getGoodsattribute());
            message.setPrice(skus.get(i).getPrice());
            System.out.println("价格" + skus.get(i).getPrice());
            message.setCount(orderdetails.get(i).getCount());
            System.out.println("数量：" + orderdetails.get(i).getCount());
            message.setCreateTime(order.getCreatetime());
            System.out.println("创建时间"+order.getCreatetime());
            message.setOderId(order.getId());
            System.out.println("订单号"+order.getId());
            message.setDetailTotalPrice(orderdetails.get(i).getTatolprice());
            System.out.println("订单详情总价格："+orderdetails.get(i).getTatolprice());
            message.setOrderTotalPrice(order.getTatolprice());
            System.out.println("订单总价格："+order.getTatolprice());
            messages.add(message);
        }
        //把messages放到session里去。
        session.setAttribute("messages", messages);


        String json = JSON.toJSONString(messages);
        System.out.println(messages);
        System.out.println("json" + json);
        response.getWriter().write(json);
    }

    /**
     * 转发支付页面
     */
    public void topay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        HttpSession session = request.getSession();
        List<Message> messages = (List<Message>) session.getAttribute("messages");
        request.getRequestDispatcher("/pay.jsp").forward(request, response);

    }

    /**
     * 改变数量
     */
    public void changeCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        System.out.println("进入changeCount");
        int out_trade_no = Integer.parseInt(new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8"));
        System.out.println("out_trade_no"+out_trade_no);
        HttpSession session = request.getSession();
        session.setAttribute("out_trade_no",out_trade_no);//out_trade_no是返回的订单id
        List<Orderdetails> orderdetails = orderServiceImpl.getGid(out_trade_no);
        boolean changeState = orderServiceImpl.changeState(out_trade_no);
        List<Integer> gid = new ArrayList<>();
        List<Integer> count = new ArrayList<>();
        for (Orderdetails temp : orderdetails) {
            gid.add(temp.getGid());
            count.add(temp.getCount());
            System.out.println("参数"+temp.getGid()+temp.getCount());
        }
        boolean isOk = orderServiceImpl.changeCount(gid,count);
        System.out.println(isOk);
        response.sendRedirect("/foraging/index.jsp");
    }



    /**
     * 获取user所有历史订单
     */
    public void getAllOrders(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        //从session里获取user的id
        HttpSession session = request.getSession();
       User user= (User) session.getAttribute("user");

        if("null".equals(user)){
            response.sendRedirect("/login.jsp");
        }


        //通过user的id，去order表查到商品详情表id
        List<Orders> orders = orderServiceImpl.getOids( user.getId());
        List<Object> objects = new ArrayList<>();
        for (Orders order:orders) {


        System.out.println("oid =" + order.getId());
        int oid = order.getId();
        //通过oid去orderdetails表里找gid，注意返回的是list
        List<Orderdetails> orderdetails = orderServiceImpl.getGid(oid);
        List<Integer> gid = new ArrayList<>();
        for (Orderdetails temp : orderdetails) {
            gid.add(temp.getGid());
        }
        System.out.println("gid =" + gid);
        //拿到gid去goods表查找商品信息
        List<Goods> goods = new ArrayList<Goods>();
        goods = orderServiceImpl.getGoodMessage(gid);
        System.out.println(goods);

        //从goods里拿分类id
        List<Integer> categoryId = new ArrayList<>();
        for (Goods temp : goods) {
            categoryId.add(temp.getCategoryid());
        }
        //到商品分类表查询分类信息
        List<Category> categorys = new ArrayList<>();
        categorys = orderServiceImpl.getCategory(categoryId);
        System.out.println("分类表信息：" + categorys);


        //从goods里拿到品牌id，在去查找品牌信息
        List<Integer> brandId = new ArrayList<>();
        for (Goods temp : goods) {
            brandId.add(temp.getBrandid());
        }
        List<Brand> brands = orderServiceImpl.getBrand(brandId);
        System.out.println("品牌表信息：" + brands);
        // 从商品分类的主键id，去Attributekey去查询

        List<Attributekey> attributekeys = orderServiceImpl.getAttributekey(categoryId);
        System.out.println("属性表信息：" + attributekeys);


        //从Attributekey表里拿到主键id，去查询value
        List<Integer> attributeId = new ArrayList<>();
        for (Attributekey temp : attributekeys) {
            attributeId.add(temp.getAttributeid());
        }
        //去value表查询
        List<Value> values = orderServiceImpl.getValue(attributeId);
        System.out.println("value值的信息：" + values);
        //查规格表
        List<Sku> skus = orderServiceImpl.getSku(gid);
        System.out.println("规格表的信息 ：" + skus);



        //实例化一个消息类，在传到前端。
        List<Message> messages = new ArrayList<>();
        for (int i = 0; gid.size() > i; i++) {
            Message message = new Message();
            message.setCategoryimg(categorys.get(i).getCategoryimg());
            System.out.println("img:" + categorys.get(i).getCategoryimg());
            message.setGoodsdescription(goods.get(i).getGoodsdescription());
            System.out.println("描述：" + goods.get(i).getGoodsdescription());
            message.setGoodsattribute(skus.get(i).getGoodsattribute());
            System.out.println("规格：" + skus.get(i).getGoodsattribute());
            message.setPrice(skus.get(i).getPrice());
            System.out.println("价格" + skus.get(i).getPrice());
            message.setCount(orderdetails.get(i).getCount());
            System.out.println("数量：" + orderdetails.get(i).getCount());
            message.setCreateTime(order.getCreatetime());
            System.out.println("创建时间"+order.getCreatetime());
            message.setOderId(order.getId());
            System.out.println("订单号"+order.getId());
            message.setOrderadress(order.getOrderadress());
            System.out.println("订单地址：" +order.getOrderadress());
            message.setPhone(user.getPhone());
            System.out.println("获取订单电话："+user.getPhone());
            message.setTakeName(user.getUsername());
            System.out.println("获取订单收货人名字："+user.getUsername());
            message.setDetailTotalPrice(orderdetails.get(i).getTatolprice());
            System.out.println("订单详情总价格："+orderdetails.get(i).getTatolprice());
            message.setOrderTotalPrice(order.getTatolprice());
            System.out.println("订单总价格："+order.getTatolprice());
            messages.add(message);
        }
        objects.add(messages);
        }
        //把messages放到session里去。
        session.setAttribute("objects", objects);
        request.getRequestDispatcher("/allOrders.jsp").forward(request,response);
    }

    /**
     * 设置订单配送地址
     */
    public void setOrder(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        System.out.println("进入setOrder");
        String orderAdress = request.getParameter("orderAdress");
        int  out_trade_no = (int) request.getSession().getAttribute("out_trade_no");
        System.out.println(orderAdress+"   "+out_trade_no);
        boolean isOk = orderServiceImpl.setOrder(orderAdress,out_trade_no);
        String json = JSON.toJSONString(isOk);
        response.getWriter().write(json);
    }

}
